const execSql = require("../../utils/DB.js")
const adminModel = require("../../model/adminModel.js")
class member {
	// 手机号获取验证码
	static async getYzm(ctx) {
		let {
			phone
		} = ctx.request.query
		const phoneRegex = /^1[3-9]\d{9}$/;
		if (phoneRegex.test(phone)) {
			// 生成验证码
			let yzm = Math.floor(100000 + Math.random() * 900000)
			let exp = new Date().getTime()+60000
			// 验证码入库
			await execSql(`INSERT INTO yzm(salt, phone, exp) VALUES ('${yzm}', '${phone}', '${exp}')`)
			ctx.body = {
				code:0,
				codeInfo:"获取成功",
				data:yzm
			}
		} else {
			ctx.body = {
				code:1,
				codeInfo:"手机号错误！"
			}
		}
	}
	
	// 手机号验证码登录
	static async telLogin(ctx){
		let {phone ,yzm} = ctx.request.body
		let nowTime = new Date().getTime()
		// 先删除所有过期的验证码
		await execSql(`delete from yzm where exp<'${nowTime}' `)
		// 数据库查询 验证码是否正确
		let res = await execSql(`select * from yzm where phone='${phone}' and salt='${yzm}' and exp>'${nowTime}'`)
		if(res.lenght>0){
			// 查询用户表 看下有没有这个用户 如果有 返回用户信息 
			let users = await execSql(`select * from member where tel='${phone}'`)
			if(users.lenght>0){
				// 说明用户存在
			}else{
				// 说明不存在 先注册
				await execSql(`INSERT INTO member(tel,nickname,username) VALUES ('${phone}','${phone}','${phone}')`)
				users = await execSql(`select * from member where tel='${phone}'`)
			}
			// 生成token
			let token = CryptoJS.MD5(`${user.id}-${psw}-${Date.now()}`).toString()
			// 过期时间30天
			let exp = Date.now() + (1000 * 60 * 60 * 24*30)
			await adminModel.addMemToken(user[0].id, token, exp)
			ctx.body = {
				code:0,
				codeInfo:"登录成功",
				data:{
					token:token,
					...users[0]
				}
			}
		}else{
			ctx.body = {
				code:1,
				codeInfo:"验证码过期，或验证码错误！"
			}
		}
	}
}
module.exports = member